package com.sky.service.impl;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //清空redis缓存
    public void redisDelKey(Long id){
        stringRedisTemplate.delete("Dish:"+id.toString());
    }

    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
        //向菜品表插入1条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);
        //获取insert语句生成的主键值
        Long dishId = dish.getId();
        //向口味表查询n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
        dishFlavorMapper.insert(flavors);
        redisDelKey(dishDTO.getCategoryId());
        }
    }

    /**
     * 分页查询全部菜品
     * @return
     */
    @Override
    public PageResult selectPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page  = dishMapper.querySelectPage(dishPageQueryDTO);
         PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;

//        String s = stringRedisTemplate.opsForValue().get("dishPage");
//        if(s == null){
//            Page<DishVO> page  = dishMapper.querySelectPage(dishPageQueryDTO);
//            PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
//            stringRedisTemplate.opsForValue().set("dishPage", JSONUtil.toJsonStr(pageResult));
//            return pageResult;
//        }
//        PageResult list = JSONUtil.toBean(s,PageResult.class);
//        return list;
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //判断当前菜品是否能够删除 -- 是否是起售中菜品
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw  new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //是否被套餐关联
        List<Long>  setmealIds = setmealDishMapper.getSetmealDishByDishIds(ids);
        if(setmealIds != null && setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的数据
        dishMapper.deleteDishById(ids);
        //删除菜品关联的口味数据
        dishFlavorMapper.deleteDishFlavorByDishId(ids);

        for (Long id : ids) {
            Dish d = dishMapper.getById(id);
            redisDelKey(d.getCategoryId());
        }

    }

    /**
     * 起售/停售
     * @param status
     * @param id
     */
    @Override
    @Transactional
    public void updStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        List<Long> ids = new ArrayList<>();
        ids.add(id);
        if (status == StatusConstant.DISABLE){
            List<Long> setmealIds = setmealDishMapper.getSetmealDishByDishIds(ids);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
        Dish d = dishMapper.getById(id);
        redisDelKey(d.getCategoryId());
    }

    @Override
    public DishVO findById(Long id) {
        DishVO dish = dishMapper.findById(id);
        return dish;
    }

    @Override
    public void updDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        List<Long> ids = new ArrayList<>();
        ids.add(dishDTO.getId());
        dishFlavorMapper.deleteDishFlavorByDishId(ids);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insert(flavors);
        }
        redisDelKey(dishDTO.getCategoryId());

    }

    @Override
    public List<Dish> list(Integer categoryId) {
        return dishMapper.dishByCategoryIdList(categoryId);
    }

    @Override
    public List<DishVO>listWithFlavor(Dish dish) {
        String key = dish.getCategoryId().toString();
        String dishListByCategoryId = stringRedisTemplate.opsForValue().get("Dish:" + key);
        //redis存在直接获取把string转为list
        if(dishListByCategoryId != null){
            List<DishVO> dishVOList = JSONUtil.toList(dishListByCategoryId,DishVO.class);
            return dishVOList;
        }
        //redis不存在直接从数据库查并存入
        List<DishVO> dishVOList = new ArrayList<>();
        List<Dish> list = dishMapper.listWithFlavor(dish);
        for (Dish d : list) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            List<DishFlavor> dishFlavorList = dishFlavorMapper.getDishFlavorByDishId(d.getId());
            dishVO.setFlavors(dishFlavorList);
            dishVOList.add(dishVO);
        }
        stringRedisTemplate.opsForValue().set("Dish:"+key,JSONUtil.toJsonStr(dishVOList));
        return dishVOList;
    }
}
